<template>
<div>
  <div id="button-box" v-if="this.$store.state.levels.length !== 0">
    <el-button type="text" id="back" @click="toRoot">根目录</el-button>
    <el-button type="text" id="back" @click="back">返回上一层</el-button>
    <el-divider direction="vertical"></el-divider>
    <el-button type="text" id="back" @click="add" v-if="this.$store.state.login.type === 3 && this.$route.query.id == 1">添加课程</el-button>
    <el-button type="text" id="back" @click="add_folder" v-if="this.$store.state.login.type === 3 && this.$route.query.id != 1 && this.$route.query.id != 2 && this.$route.query.id != 4">新建文件夹</el-button>
  </div>
  <el-table
    :data="tableData"
    style="width: 100%">
    <el-table-column
      width="60">
      <template slot-scope="scope">
        <div class="icon" :class="scope.row.type"></div>
      </template>
    </el-table-column>
    <el-table-column
      width="380">
      <template slot-scope="scope">
        {{ scope.row.name }}
      </template>
    </el-table-column>
    <el-table-column
      v-if="$store.state.login.type === 3">
      <template slot-scope="scope">
        <el-link type="danger" @click="handleDetele(scope.row)">删除</el-link>
        <!-- <el-link type="primary" @click="handleChange(scope.row)">修改</el-link> -->
      </template>
    </el-table-column>
    <el-table-column
      width="180">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="openDialog(scope.row)"
          v-if="scope.row.type !== 'folder'"
          >更新</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="enterFolder(scope.$index, scope.row)"
          v-if="scope.row.type === 'folder'"
          >进入目录</el-button>
        <el-button
          size="mini"
          type="success"
          @click="getDetail(scope.$index, scope.row)"
          v-if="scope.row.type !== 'folder'"
          >查看详情</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 版本更新模态框 -->
  <el-dialog title="资产版本更新" :visible.sync="uploadFormVisible">
    <el-form :model="uploadForm" :rules="uploadRules" ref="form">
        <el-form-item label="版本号" :label-width="formLabelWidth" prop="version">
            <el-input v-model="uploadForm.version" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文件上传" :label-width="formLabelWidth">
          <el-upload
              class="upload-demo"
              drag
              action=""
              :file-list="fileList"
              :auto-upload="false"
              :multiple="false"
              ref="upload"
              :limit="1"
              :on-exceed="handleExceed"
              :on-remove="handleRemove"
              >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">不限制文件类型，大小不超过500MB<br/>只支持单文件上传，若您有多个文件，请先将其打包为压缩包</div>
          </el-upload>
          <el-progress :percentage="percentage" :status="upload_status" v-if="percentage_visibility"></el-progress>
          <el-button type="primary" size="mini" id="upload-button-inner" @click="submitUpload">上传<i class="el-icon-upload el-icon--right"></i></el-button>
        </el-form-item>
        <el-form-item label="更新日志" :label-width="formLabelWidth" prop="desc">
            <el-input type="textarea" v-model="uploadForm.desc"></el-input>
        </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="update">确认并提交审核</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script>
import axios from 'axios'
  export default {
    name:'List',
    data() {
      return {
        tableData: [],
        // 资源更新
        uploadForm: {
          version:'',
          desc:''
        },
        formLabelWidth: '120px',
        uploadFormVisible:false,
        uploadRules:{
          version:[
            {required: true,message: '请输入版本号', trigger: 'blur'},
            {
              validator:function(rule, value, callback){
                let reg = /^\d+(\.\d+)?$/;
                if(!reg.test(value)){
                  callback('只能输入数字和小数点，只允许存在一层子版本号，例如：2.1');
                }else{
                  callback();
                }
              }
            }
          ],
          desc:[
            { required: true, message: '请输入资产描述', trigger: 'blur' },
            { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' }
          ]
        },
        // 文件上传
        fileList:[],
        // 上传进度
        percentage:0,
        upload_status:null,
        percentage_visibility:false,
        // 文件上传成功标志位
        upload_success_tag:false,
        // 文件上传回执信息
        upload_callback:null,
        // 选择的文件
        file_id:''
      }
    },
    created:function(){
      this.getData(this.$route.query.id);
    },
    watch: {
      // 监听路由，调用详情方法
      $route( to , from ){ 
        this.getData(this.$route.query.id);
        // console.log("watch working......");
      }
    },
    methods: {
      // 获取该文件夹的字文件夹和文件
      getData:async function(id){
        try{
          const res = await axios.get('/api/common/enter?fid='+id+'&type=0',{headers: {'x-auth-token': this.$store.state.login.token}});
          // console.log(res);
          let new_data = [];
          if(res.status!==200) return this.$message.error("加载失败，请检查网络！");
          if(res.data.res.ok === 1){
            // 处理文件夹
            if(res.data.res.data[0].length > 0){
              for(let i in res.data.res.data[0]){
                let temp = {
                  type: 'folder',
                  name: res.data.res.data[0][i].name,
                  id: res.data.res.data[0][i].fid,
                };
                new_data.push(temp);
              }
            }
            // 处理文件
            if(res.data.res.data[1].length > 0){
              for(let i in res.data.res.data[1]){
                let temp = {
                  type: res.data.res.data[1][i].type,
                  name: res.data.res.data[1][i].name,
                  id: res.data.res.data[1][i].file_id,
                };
                new_data.push(temp);
              }
            }
            this.tableData = new_data;
          }else{
            this.$message.error(res.data.res.msg);
          }
        }catch(e){
          console.log(e);
          this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
        };
      },
      // 进入文件夹
      enterFolder(index,row){
        this.$store.commit('nextLevel',row.id);
        // this.getData(row.id);
        this.$router.push({ path: 'list',query:{'id':row.id} });
      },
      // 文件上传
      submitUpload:function() {
        this.percentage_visibility = true;
        const formData = new FormData();
        const file = this.$refs.upload.uploadFiles[0];
        const headerConfig = { headers:
          { 'Content-Type': 'multipart/form-data' ,'x-auth-token': this.$store.state.login.token},
          onUploadProgress: progressEvent => {
            if(progressEvent.lengthComputable){
              let val = parseInt(
                (
                  (progressEvent.loaded / progressEvent.total)*100
                ).toFixed(0)
              );//获取百分比
              this.percentage = val;
              if(val == 100){
                this.upload_status = 'success';
              }
            }
          }
        }
        if (!file) { // 若未选择文件
          alert('请选择文件')
          return
        }
        formData.append('file', file.raw)
        axios.post('/api/upload/single', formData, headerConfig).then(res => {
          console.log(res);
          this.$notify({
            title: '提示',
            message: res.data.res.msg,
            type: res.data.res.status
          });
          if(res.data.res.ok === 1){
            this.upload_success_tag = true;
            this.upload_callback = res.data.res;
          }
        })
      },
      // 用户多选了多个文件
      handleExceed(files, fileList) {
          this.$message.warning(`只允许选择1个文件，若有多个文件需要上传，请打包为压缩包后再上传！`);
      },
      // 从文件上传列表移除文件
      handleRemove(file, fileList){
          this.percentage = 0;
          this.percentage_visibility = false;
      },
      // 跳转资源详情页
      getDetail(index,row){
        this.$router.push({ path: '/detail',query:{'id':row.id} });
      },
      // 打开资源更新窗口
      openDialog(row){
        this.uploadFormVisible = true;
        this.file_id = row.id;
      },
      // 资源版本更新
      update() {
        this.$refs.form.validate(async (valid) => {
          if(!valid) {
              this.$message.error("信息为填写完整或未按要求填写，请根据红色文字提示修改后再进行提交！");
              return;
          }
          let post_data = {
              file_id:this.file_id,
              version:this.$data.uploadForm.version,
              desc:this.$data.uploadForm.desc,
              originalname:this.upload_callback.originalname,
              uploader:this.$store.state.login.uid,
              path:this.upload_callback.path,
              size:this.upload_callback.size
          }
          const headerConfig = { headers:
              { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
          };
          try{
              const res = await axios.post('/api/upload/file_update',post_data,headerConfig);
              if(res.status!==200) return this.$message.error("提交失败，请检查网络设置！");
              if(res.data.res.ok === 1){
                  this.$notify({
                      title: '提交成功',
                      message: "提交成功！您更新的资源正在等待管理员审核，审核结果可以在'我的——个人中心——消息中心'中找到",
                      type: 'success'
                  });
              }else{
                  this.$notify({
                      title: '提交失败',
                      message: res.data.res.msg,
                      type: 'error'
                  });
              }
          }catch(e){
              console.log(e);
              this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
          }
        });
        this.uploadFormVisible = false;
      },
      handleDetele:function(row){
        this.$confirm('此操作将删除该项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          console.log(row);
          let post_data = {
            type:row.type,
            uid:this.$store.state.login.uid,
            id:row.id
          }
          console.log(post_data)
          const headerConfig = { headers:
              { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
          };
          try{
              const res = await axios.post('/api/common/delete',post_data,headerConfig);
              if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
              if(res.data.res.ok === 1){
                  this.$notify({
                      title: '提示',
                      message: res.data.res.msg,
                      type: 'success'
                  });
                  this.$router.go(0);
              }else{
                  this.$notify({
                      title: '提示',
                      message: res.data.res.msg,
                      type: 'error'
                  });
              }
          }catch(e){
              console.log(e);
              this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
          }
        }).catch(() => {
          this.$message({
              type: 'info',
              message: '已取消操作'
          });          
        });
      },
      toRoot:function(){
        this.$router.push({ path: '/library/root' })
      },
      back:function(){
        this.$store.commit('lastLevel');
        // console.log("现在的参数是："+this.$store.state.levels[this.$store.state.levels.length-1]);
        if (typeof(this.$store.state.levels[this.$store.state.levels.length-1]) == "undefined"){
          this.$router.push({ path: '/library/root'});
          return;
        }
        this.$router.push({ path: 'list',query:{'id':this.$store.state.levels[this.$store.state.levels.length-1]} });
      },
      add:function(){
        this.$prompt('请输入课程名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[0-9\u4e00-\u9fffa-zA-Z]{1,30}$/,
          inputErrorMessage: '请输入长度1-30字符的合法课程名称'
        }).then(async ({ value }) => {
            let post_data = {
                name:value,
                fid:this.$route.query.id
            }
            const headerConfig = { headers:
                { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
                const res = await axios.post('/api/common/add_course',post_data,headerConfig);
                if(res.status!==200) return this.$message.error("提交失败，请检查网络设置！");
                if(res.data.res.ok === 1){
                    this.$notify({
                        title: '成功',
                        message: res.data.res.msg,
                        type: 'success'
                    });
                    this.$router.go(0);
                }else{
                    this.$notify({
                        title: '失败',
                        message: res.data.res.msg,
                        type: 'error'
                    });
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
      },
      add_folder:function(){
        this.$prompt('请输入文件夹名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[0-9\u4e00-\u9fffa-zA-Z]{1,30}$/,
          inputErrorMessage: '请输入长度1-30字符的合法文件夹名称'
        }).then(async ({ value }) => {
            let post_data = {
                name:value,
                lastlevel:this.$route.query.id
            }
            const headerConfig = { headers:
                { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
                const res = await axios.post('/api/common/add_folder',post_data,headerConfig);
                if(res.status!==200) return this.$message.error("提交失败，请检查网络设置！");
                if(res.data.res.ok === 1){
                    this.$notify({
                        title: '成功',
                        message: res.data.res.msg,
                        type: 'success'
                    });
                    this.$router.go(0);
                }else{
                    this.$notify({
                        title: '失败',
                        message: res.data.res.msg,
                        type: 'error'
                    });
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
@import "../../../assets/css/file.css";
#button-box{
  margin-left:5px;
}
.icon{
  display: inline-block;
  width:40px;
  height: 40px;
  background-size:40px 40px;
  background-repeat:no-repeat;
  background-position:top center;
  background-color: transparent;
}
</style>